<script setup>
import {ref, onMounted} from "vue";
import api from '../api/warehouse.js';

// 页面数据
const pageData = ref({
  records: [],
  total: 0,
  size: 10,
  current: 1,
  pages: 1
});

// 搜索文本
const searchText = ref('');

// 对话框控制
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const deleteDialogVisible = ref(false);

// 表单对象
const addObj = ref({
  wlocation: '北京',
  wquantity: '',
  wuser: '',
  wmaxcapacity: '',
  wname: ''
});

const editObj = ref({
  wid: '',
  wlocation: '',
  wquantity: '',
  wuser: '',
  wmaxcapacity: '',
  wname: ''
});

const deleteObj = ref({
  wid: '',
  wname: ''
});

// 计算进度百分比（确保值在0-100之间）
const calculatePercentage = (quantity, capacity) => {
  // 处理非数值和除数为0的情况
  if (isNaN(quantity) || isNaN(capacity) || capacity <= 0) return 0;

  const percentage = (quantity / capacity) * 100;
  // 确保结果在0-100之间
  return Math.min(100, Math.max(0, Math.round(percentage)));
}

// 生命周期钩子
onMounted(() => {
  getTableList();
});

// 获取表格数据
const getTableList = async () => {
  const params = {
    current: pageData.value.current,
    size: pageData.value.size,
    searchtext: searchText.value || ''
  };

  try {
    const result = await api.getWarehousePage(params);
    pageData.value = result;
  } catch (error) {
    console.error("获取仓库数据失败:", error);
  }
};

// 分页处理
const handleSizeChange = (size) => {
  pageData.value.size = size;
  pageData.value.current = 1;
  getTableList();
};

const handleCurrentChange = (current) => {
  pageData.value.current = current;
  getTableList();
};

// 搜索处理
const handleSearch = () => {
  pageData.value.current = 1;
  getTableList();
};

// 删除仓库
const handleDelete = (row) => {
  deleteObj.value = {
    wid: row.wid,
    wname: row.wname
  };
  deleteDialogVisible.value = true;
};

const confirmDelete = async () => {
  try {
    await api.deleteWarehouse(deleteObj.value.wid);
    getTableList();
    deleteDialogVisible.value = false;
  } catch (error) {
    console.error("删除仓库失败:", error);
  }
};

// 编辑仓库
const handleEdit = (row) => {
  editDialogVisible.value = true;
  editObj.value = {...row};
};

const handlerEditConfirm = async () => {
  try {
    // 确保数值类型
    const submitData = {
      ...editObj.value,
      wquantity: Number(editObj.value.wquantity),
      wmaxcapacity: Number(editObj.value.wmaxcapacity)
    };

    await api.editWarehouse(submitData);
    getTableList();
    editDialogVisible.value = false;
  } catch (error) {
    console.error("更新仓库失败:", error);
  }
};

// 新增仓库
const handlerAddConfirm = async () => {
  try {
    // 确保数值类型
    const submitData = {
      ...addObj.value,
      wquantity: Number(addObj.value.wquantity),
      wmaxcapacity: Number(addObj.value.wmaxcapacity)
    };

    await api.addWarehouse(submitData);
    getTableList();
    addDialogVisible.value = false;
    // 重置表单
    addObj.value = {
      wlocation: '北京',
      wquantity: '',
      wuser: '',
      wmaxcapacity: '',
      wname: ''
    };
  } catch (error) {
    console.error("添加仓库失败:", error);
  }
};

// 取消操作
const handlerAddCancel = () => {
  addDialogVisible.value = false;
  addObj.value = {
    wlocation: '北京',
    wquantity: '',
    wuser: '',
    wmaxcapacity: '',
    wname: ''
  };
};

const handlerEditCancel = () => {
  editDialogVisible.value = false;
};
</script>

<template>
  <div class="warehouse-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">仓库管理</h2>
      <p class="page-subtitle">管理仓库信息和库存容量</p>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="global-card operation-card">
      <el-row :gutter="20" align="middle">
        <el-col :span="8">
          <el-input
              v-model="searchText"
              placeholder="搜索仓库ID/名称"
              clearable
              @clear="handleSearch"
          >
            <template #prefix>
              <el-icon class="search-icon">
                <Search/>
              </el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch" class="action-button">
            <el-icon>
              <Search/>
            </el-icon>
            查询
          </el-button>
        </el-col>
        <el-col :span="4" :offset="8">
          <el-button type="success" @click="addDialogVisible = true" class="action-button new-warehouse-button">
            <el-icon>
              <Plus/>
            </el-icon>
            新增仓库
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 仓库表格 -->
    <div class="global-card data-card">
      <el-table :data="pageData.records" style="width: 100%" stripe height="calc(100vh - 280px)">
        <el-table-column prop="wid" label="仓库ID" width="120" align="center"/>
        <el-table-column prop="wname" label="仓库名称" width="180" align="center">
          <template #default="{ row }">
            <el-tag type="info" class="warehouse-tag">{{ row.wname }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="wuser" label="管理员" width="120" align="center"/>
        <el-table-column prop="wlocation" label="位置" width="150" align="center"/>
        <el-table-column prop="wquantity" label="当前库存" width="120" align="center"/>
        <el-table-column prop="wmaxcapacity" label="最大容量" width="120" align="center"/>
        <el-table-column label="使用率" width="180" align="center">
          <template #default="{ row }">
            <el-progress
                :percentage="calculatePercentage(row.wquantity, row.wmaxcapacity)"
                :color="row.wquantity / row.wmaxcapacity > 0.9 ? '#f56c6c' : '#67c23a'"
                :text-inside="true"
                :stroke-width="20"
                :format="(percent) => `${percent}%`"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
                size="small"
                @click="handleEdit(row)"
                icon="Edit"
                class="edit-button"
            >编辑
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(row)"
                icon="Delete"
                class="delete-button"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <el-pagination
            v-model:current-page="pageData.current"
            v-model:page-size="pageData.size"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageData.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="custom-pagination"
        />
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog
        v-model="deleteDialogVisible"
        title="确认删除仓库"
        width="400px"
        class="delete-dialog"
    >
      <div class="dialog-content">
        <el-icon class="dialog-icon" color="#F56C6C">
          <WarningFilled/>
        </el-icon>
        <p>确定要删除仓库 <strong>{{ deleteObj.wname }}</strong> 吗？</p>
        <p class="warning-text">此操作不可恢复，请谨慎操作！</p>
      </div>
      <template #footer>
        <el-button @click="deleteDialogVisible = false" class="cancel-button">取消</el-button>
        <el-button type="danger" @click="confirmDelete" class="confirm-delete-button">确认删除</el-button>
      </template>
    </el-dialog>

    <!-- 新增仓库对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增仓库" class="form-dialog">
      <div class="dialog-header">
        <el-icon>
          <OfficeBuilding/>
        </el-icon>
        <span>添加新仓库信息</span>
      </div>
      <el-form :model="addObj" label-width="100px" class="warehouse-form">
        <el-form-item label="仓库名称">
          <el-input v-model="addObj.wname" autocomplete="off" placeholder="请输入仓库名称"/>
        </el-form-item>
        <el-form-item label="管理员">
          <el-input v-model="addObj.wuser" autocomplete="off" placeholder="请输入管理员姓名"/>
        </el-form-item>
        <el-form-item label="位置">
          <el-input v-model="addObj.wlocation" autocomplete="off" placeholder="请输入仓库位置"/>
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input-number v-model="addObj.wquantity" :min="0" :max="addObj.wmaxcapacity || 99999"/>
        </el-form-item>
        <el-form-item label="最大容量">
          <el-input-number v-model="addObj.wmaxcapacity" :min="1" :max="10000"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handlerAddCancel" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="handlerAddConfirm" class="confirm-button">确认新增</el-button>
      </template>
    </el-dialog>

    <!-- 编辑仓库对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑仓库" class="form-dialog">
      <div class="dialog-header">
        <el-icon>
          <Edit/>
        </el-icon>
        <span>编辑仓库信息</span>
      </div>
      <el-form :model="editObj" label-width="100px" class="warehouse-form">
        <el-form-item label="仓库ID">
          <el-input v-model="editObj.wid" disabled/>
        </el-form-item>
        <el-form-item label="仓库名称">
          <el-input v-model="editObj.wname" autocomplete="off" placeholder="请输入仓库名称"/>
        </el-form-item>
        <el-form-item label="管理员">
          <el-input v-model="editObj.wuser" autocomplete="off" placeholder="请输入管理员姓名"/>
        </el-form-item>
        <el-form-item label="位置">
          <el-input v-model="editObj.wlocation" autocomplete="off" placeholder="请输入仓库位置"/>
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input-number v-model="editObj.wquantity" :min="0" :max="editObj.wmaxcapacity"/>
        </el-form-item>
        <el-form-item label="最大容量">
          <el-input-number v-model="editObj.wmaxcapacity" :min="1" :max="10000"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handlerEditCancel" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="handlerEditConfirm" class="confirm-button">保存修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.warehouse-management {
  padding: 20px;
  background-color: #f0f7ff;
  min-height: calc(100vh - 60px);
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #d1e5f9;
}

.page-title {
  color: #1a3b6d;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
}

.page-subtitle {
  color: #4a7bb9;
  font-size: 15px;
}

/* 卡片样式 */
.operation-card {
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  background-color: #ffffff;
}

.data-card {
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  background-color: #ffffff;
}

/* 按钮样式 */
.action-button {
  padding: 8px 15px;
  font-weight: 500;
  transition: all 0.3s;
  border-radius: 8px;
  font-size: 14px;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.new-warehouse-button {
  background: linear-gradient(135deg, #1890ff, #40a9ff);
  border: none;
  color: white;
}

.new-warehouse-button:hover {
  background: linear-gradient(135deg, #096dd9, #1890ff);
}

.edit-button {
  background-color: #e3f2fd;
  border-color: #90caf9;
  color: #1565c0;
}

.delete-button {
  background-color: #ffebee;
  border-color: #ffcdd2;
  color: #1565c0;
}

/* 标签样式 */
.warehouse-tag {
  background-color: #e8f4ff;
  border-color: #91d5ff;
  color: #1890ff;
  padding: 4px 10px;
  font-weight: 500;
}

/* 分页样式 */
.pagination-wrapper {
  padding: 20px;
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.custom-pagination {
  background: white;
  padding: 10px 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 对话框样式 */
.delete-dialog {
  border-radius: 10px;
  background: linear-gradient(to bottom, #ffffff, #f8fbff);
}

.dialog-content {
  text-align: center;
  padding: 20px;
}

.dialog-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.warning-text {
  color: #e74c3c;
  font-size: 14px;
  margin-top: 10px;
}

.form-dialog {
  border-radius: 12px;
  background: linear-gradient(to bottom, #ffffff, #f8fbff);
}

.dialog-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e1ecf7;
}

.dialog-header .el-icon {
  font-size: 24px;
  margin-right: 10px;
  color: #1890ff;
}

.dialog-header span {
  font-size: 18px;
  font-weight: 600;
  color: #1a3b6d;
}

.warehouse-form {
  padding: 0 20px;
}

/* 按钮样式 */
.cancel-button {
  background-color: #f5f7fa;
  border-color: #e1ecf7;
  color: #5a7ea9;
  margin-right: 15px;
}

.confirm-button {
  background: linear-gradient(135deg, #1890ff, #40a9ff);
  border: none;
  color: white;
}

.confirm-button:hover {
  background: linear-gradient(135deg, #096dd9, #1890ff);
}

.confirm-delete-button {
  background: linear-gradient(135deg, #e53935, #d32f2f);
  border: none;
  color: white;
}

.confirm-delete-button:hover {
  background: linear-gradient(135deg, #d32f2f, #c62828);
}

/* 输入框样式 */
.search-icon {
  color: #1890ff;
  font-size: 18px;
}

/* 进度条样式 */
.el-progress {
  margin: 5px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .operation-card .el-row .el-col {
    margin-bottom: 10px;
  }

  .operation-card .el-col:last-child {
    margin-bottom: 0;
  }

  .new-warehouse-button {
    width: 100%;
  }

  .el-col:first-child {
    width: 100%;
    margin-bottom: 15px;
  }

  .el-table {
    font-size: 12px;
  }

  .el-table-column {
    padding: 4px !important;
  }
}
</style>